package com.hq.ims.data.aop;

import com.hq.authority.utils.AppUtils;
import com.hq.ims.data.entity.Company;
import com.hq.ims.data.entity.CompanyEmployee;
import com.hq.ims.data.entityenum.EnumAuditStatus;
import com.hq.ims.data.service.BaseCompanyEmployeeService;
import com.hq.ims.data.service.BaseCompanyService;
import com.hq.ims.data.utils.LocalConstant;
import com.hq.utils.util.ObjectUtils;
import com.hq.utils.util.StringUtils;
import com.hq.web.inf.user.ITokenUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
@Slf4j
public class CompanyUnauditedAop {

    @Resource
    private BaseCompanyService companyService;
    @Resource
    private BaseCompanyEmployeeService baseCompanyEmployeeService;

    public CompanyUnauditedAop() {
    }

    @Before(value = "@annotation(com.hq.ims.data.annotation.CompanyUnaudited)")
    public void doBefore(JoinPoint joinPoint) {
        ITokenUserInfo currentUser = AppUtils.getCurrentUser();
        ObjectUtils.isNullThrow(currentUser,"用户信息异常！");
        if (StringUtils.isEmpty(currentUser.getId())){
            throw new RuntimeException("用户信息异常，请重新登录！");
        }
        CompanyEmployee employee = baseCompanyEmployeeService.lambdaQuery()
                .eq(CompanyEmployee::getUserId, currentUser.getId())
                .orderByAsc(CompanyEmployee::getCreateDateTime)
                .last(LocalConstant.LIMIT_1)
                .one();
        ObjectUtils.isNullThrow(employee,"用户信息异常！");
        if (StringUtils.isEmpty(employee.getCompanyId())){
            throw new RuntimeException("公司信息异常，请重新登录！");
        }
        Company company = companyService.getById(employee.getCompanyId());
        ObjectUtils.isNullThrow(company,"公司信息异常，请重新登录！");
        if (company.getAuditStatus().getCode()== EnumAuditStatus.UnderReview.getCode()){
            throw new RuntimeException("公司信息审核中不允许操作！");
        }

    }
}
